import React, { useState } from 'react';
import { Loader2, Check, PlusCircle, Edit, Key, BarChart, X } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useTranslations } from 'next-intl';
import { ProgressBar } from '@/components/project/progress-bar';
import { post } from '@/lib/request';
import { Project } from '@/controller/project';
import { toast } from 'sonner';

interface SearchConfirmationProps {
  onConfirmSearch: (selectedKeywords: string[], evaluationCriteria: string[]) => void;
  isEditing?: boolean;
  id: string;
  initialKeywords: string[];
  initialEvaluationCriteria: string[];
}

export default function SearchConfirmation({ onConfirmSearch, id, initialKeywords, initialEvaluationCriteria }: SearchConfirmationProps) {
  const t = useTranslations('project');
  const commonT = useTranslations('common');
  const [searchCompleted, setSearchCompleted] = useState(initialKeywords.length > 0);
  const [isLoading, setIsLoading] = useState(false);
  // 关键词选项 - 由AI生成的建议关键词
  const [suggestedKeywords, setSuggestedKeywords] = useState<string[]>(initialKeywords);
  // 用户自定义的关键词
  const [customKeywords, setCustomKeywords] = useState<string[]>([]);
  // 所有关键词（建议+自定义）
  const allKeywords = [...suggestedKeywords, ...customKeywords];
  // 选中的关键词
  const [selectedKeywords, setSelectedKeywords] = useState<string[]>(initialKeywords);
  // 新关键词输入
  const [newKeyword, setNewKeyword] = useState('');
  // 评估标准
  const [evaluationCriteria, setEvaluationCriteria] = useState<string[]>(initialEvaluationCriteria);
  // 新评估标准
  const [newCriterion, setNewCriterion] = useState('');
  // 添加自定义关键词
  const handleAddKeyword = () => {
    if (newKeyword.trim()) {
      const newKeywordText = newKeyword.trim();
      setCustomKeywords(prev => [...prev, newKeywordText]);
      setSelectedKeywords(prev => [...prev, newKeywordText]);
      setNewKeyword('');
    }
  };

  // 删除关键词
  const handleRemoveKeyword = (keyword: string) => {
    // 从自定义关键词中删除
    setCustomKeywords(prev => prev.filter(k => k !== keyword));
    // 从选中关键词中删除
    setSelectedKeywords(prev => prev.filter(k => k !== keyword));
  };
  // 处理关键词选择变化
  const handleKeywordChange = (keyword: string, checked: boolean) => {
    if (checked) {
      setSelectedKeywords(prev => [...prev, keyword]);
    } else {
      setSelectedKeywords(prev => prev.filter(k => k !== keyword));
    }
  };
  // 添加自定义评估标准
  const handleAddCriterion = () => {
    if (newCriterion.trim()) {
      setEvaluationCriteria(prev => [...prev, newCriterion.trim()]);
      setNewCriterion('');
    }
  };

  // 评估标准编辑状态管理
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [editingValue, setEditingValue] = useState<string>('');

  // 切换评估标准编辑状态
  const toggleCriterionEdit = (index: number) => {
    if (editingIndex === index) {
      // 如果已经在编辑这个标准，则保存并退出编辑模式
      if (editingValue.trim()) {
        updateCriterion(index, editingValue.trim());
      }
      setEditingIndex(null);
      setEditingValue('');
    } else {
      // 进入编辑模式
      setEditingIndex(index);
      setEditingValue(evaluationCriteria[index]);
    }
  };

  // 删除评估标准
  const removeCriterion = (index: number) => {
    setEvaluationCriteria(prev => prev.filter((_, i) => i !== index));
  };

  // 更新评估标准
  const updateCriterion = (index: number, newValue: string) => {
    setEvaluationCriteria(prev => {
      const updated = [...prev];
      updated[index] = newValue;
      return updated;
    });
  };

  // 确认搜索
  const handleConfirmSearch = async () => {
    setIsLoading(true);
    try {
      await post('/tasks/create', {
        project_id: id,
        "task_type": "content_search_flow",
        "input_data": {
          "keywords": selectedKeywords
      }
    })
    onConfirmSearch(selectedKeywords, evaluationCriteria);
    } catch (error) {
      toast.error('Failed to create task');
    } finally {
      setIsLoading(false);
    }
    
    // get(`/ai?projectId=${id}`).then(() => {
      
    // }).catch(error => {
    //   console.error('AI请求失败:', error);
    //   setIsLoading(false);
    // });
  };
  return (
    <div>
      {/* 搜索确认区域 - 从弹窗移到页面中 */}
      <div className="mt-4 border rounded-lg p-4 bg-white shadow-sm">
        {searchCompleted && suggestedKeywords.length > 0 ? (
          <>
            <div className="mb-3">
              <h2 className="text-xl font-semibold">{t('title')}</h2>
              <p className="text-sm text-muted-foreground">{t('keywordsGenerated')}</p>
            </div>

            <Tabs defaultValue="keywords" className="mt-4">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="keywords" className="flex items-center gap-1">
                  <Key className="h-4 w-4" />
                  {t('keywordsTab')}
                </TabsTrigger>
                <TabsTrigger value="criteria" className="flex items-center gap-1">
                  <BarChart className="h-4 w-4" />
                  {t('criteriaTab')}
                </TabsTrigger>
              </TabsList>

              {/* 关键词确认区块 */}
              <TabsContent value="keywords" className="space-y-4 py-4">
                <div>
                  <h3 className="text-base font-medium flex items-center gap-2 mb-2">
                    <Key className="h-4 w-4 text-blue-500" />
                    {t('keywordsQuestion')}
                  </h3>

                  {/* 关键词标签列表 */}
                  <div className="flex flex-wrap gap-2 mb-3">
                    {allKeywords.map((keyword) => (
                      <Badge
                        key={keyword}
                        data-keyword={keyword}
                        variant={selectedKeywords.includes(keyword) ? "default" : "outline"}
                        className={`cursor-pointer ${selectedKeywords.includes(keyword) ? '' : 'bg-gray-100 hover:bg-gray-200'}`}
                        onClick={() => handleKeywordChange(keyword, !selectedKeywords.includes(keyword))}
                      >
                        {keyword}
                        {customKeywords.includes(keyword) && (
                          <X
                            className="ml-1 h-3 w-3 hover:text-red-500"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleRemoveKeyword(keyword);
                            }}
                          />
                        )}
                      </Badge>
                    ))}
                  </div>

                  {/* 添加新关键词 */}
                  <div className="flex gap-2">
                    <Input
                      value={newKeyword}
                      onChange={(e) => setNewKeyword(e.target.value)}
                      placeholder={t('addKeywordPlaceholder')}
                      className="flex-1"
                      onKeyDown={(e) => e.key === 'Enter' && handleAddKeyword()}
                    />
                    <Button
                      size="sm"
                      onClick={handleAddKeyword}
                      disabled={!newKeyword.trim()}
                    >
                      <PlusCircle className="h-4 w-4 mr-1" />
                      {t('addButton')}
                    </Button>
                  </div>

                  <p className="text-xs text-muted-foreground mt-2">
                    {t('keywordsDescription')}
                  </p>
                </div>
              </TabsContent>

              {/* 评估标准确认区块 */}
              <TabsContent value="criteria" className="space-y-4 py-4">
                <div>
                  <h3 className="text-base font-medium flex items-center gap-2 mb-3">
                    <BarChart className="h-4 w-4 text-green-500" />
                    {t('criteriaQuestion')}
                  </h3>

                  {/* 评估标准卡片列表 */}
                  <div className="space-y-3">
                    {evaluationCriteria.map((criterion, index) => (
                      <Card key={index} className="overflow-hidden">
                        <CardContent className="p-3 flex items-center justify-between">
                          {editingIndex === index ? (
                            <div className="flex-1 flex items-center gap-2">
                              <Input
                                className="flex-1 h-8"
                                value={editingValue}
                                onChange={(e) => setEditingValue(e.target.value)}
                                placeholder="编辑评估标准..."
                                autoFocus
                                onKeyDown={(e) => {
                                  if (e.key === 'Enter' && editingValue.trim()) {
                                    updateCriterion(index, editingValue.trim());
                                    setEditingIndex(null);
                                  } else if (e.key === 'Escape') {
                                    setEditingIndex(null);
                                    setEditingValue('');
                                  }
                                }}
                              />
                            </div>
                          ) : (
                            <div className="flex items-center gap-2">
                              <Check className="h-4 w-4 text-green-500" />
                              <span className="text-sm">{criterion}</span>
                            </div>
                          )}
                          <div className="flex items-center gap-1">
                            {editingIndex === index ? (
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 w-8 p-0"
                                onClick={() => {
                                  if (editingValue.trim()) {
                                    updateCriterion(index, editingValue.trim());
                                  }
                                  setEditingIndex(null);
                                  setEditingValue('');
                                }}
                              >
                                <Check className="h-3.5 w-3.5 text-green-500" />
                              </Button>
                            ) : (
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 w-8 p-0"
                                onClick={() => toggleCriterionEdit(index)}
                              >
                                <Edit className="h-3.5 w-3.5" />
                              </Button>
                            )}
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0 hover:text-red-500"
                              onClick={() => removeCriterion(index)}
                            >
                              <X className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>

                  {/* 添加自定义标准 */}
                  <div className="flex gap-2 mt-3">
                    <Input
                      value={newCriterion}
                      onChange={(e) => setNewCriterion(e.target.value)}
                      placeholder={t('addCustomCriteriaPlaceholder')}
                      className="flex-1"
                      onKeyDown={(e) => e.key === 'Enter' && handleAddCriterion()}
                    />
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={handleAddCriterion}
                      disabled={!newCriterion.trim()}
                    >
                      <PlusCircle className="h-4 w-4 mr-1" />
                      {commonT('add')}
                    </Button>
                  </div>

                  <p className="text-xs text-muted-foreground mt-2">
                    {t('criteriaDescription')}
                  </p>
                </div>
              </TabsContent>
            </Tabs>

            {/* 底部按钮 */}
            <div className="mt-4">
              <Button
                onClick={handleConfirmSearch}
                className="w-full"
                disabled={selectedKeywords.length === 0 || isLoading || editingIndex !== null}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    {t('loading')}
                  </>
                ) : (
                  t('confirmSearch', { count: selectedKeywords.length })
                )}
              </Button>
            </div>
          </>

        ) : (
          <>
            <div className="mb-3">
              <h2 className="text-xl font-semibold">{t('generatingKeywords')}</h2>
            </div>
            <ProgressBar
              projectId={id as string}
              onSearchCompleted={(flag: boolean, projectData: Project | null) => {
                console.log("🚀 ~ file: search-confirmation.tsx:329 ~ flag:", flag)
                setSearchCompleted(flag)
                // 如果有项目数据，更新关键词和评估标准
                if (projectData) {
                  // 处理AI生成的建议关键词
                  if (projectData.search_keywords && projectData.search_keywords.length > 0) {
                    setSuggestedKeywords(projectData.search_keywords);
                    // 默认选中所有AI生成的关键词
                    setSelectedKeywords(projectData.search_keywords);
                  }

                  // 处理AI生成的评估标准
                  if (projectData.matching_rules && projectData.matching_rules.length > 0) {
                    // 直接使用字符串数组
                    setEvaluationCriteria(projectData.matching_rules);
                  }
                }
              }}
              title={t('generatingKeywords')} />
          </>
        )}
      </div>
    </div>
  );
}